<?php

namespace App\Service\AppService;

use App\Service\BaseService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Service\TraitService\AliYunOssFileUploadTrait;
use function EasySwoole\Spl\explode;
use App\Service\Code\Normal;

/**
 * excel 服务类 
 * @author chenshubo
 */
class ExportExcelHandleService extends BaseService
{  
    use AliYunOssFileUploadTrait;
    private $sheet;
    private $spreadsheet;
    private $row;
    //构造函数 创建一个PhpSpreadsheet实例
    public function __init()
    {
        // Create new Spreadsheet object
        $this->spreadsheet = new Spreadsheet();
        // Set document properties
        $this->spreadsheet->getProperties()->setCreator('Maarten Balliauw')
        ->setLastModifiedBy('Maarten Balliauw')
        ->setTitle('Office 2007 XLSX Test Document')
        ->setSubject('Office 2007 XLSX Test Document')
        ->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
        ->setKeywords('office 2007 openxml php')
        ->setCategory('Test result file');
        
        // Add some data
        $this->spreadsheet->setActiveSheetIndex(0);
        $this->sheet = $this->spreadsheet->getActiveSheet();
        
        // Rename worksheet
        $this->spreadsheet->getActiveSheet()->setTitle('Sheet1');
    }
    
    //设置表头
    public function setHeader($title)
    {
        $colum = 'A';
        foreach ($title as $v) 
        {
            $this->sheet->setCellValue($colum . '1', $v);
            $this->sheet->getColumnDimension($colum)->setWidth(40);
            $colum++;
        }
        
        /* foreach ($title as $key => $item) {
            $this->sheet->setCellValue(chr($key + 65) . '1', $item);
        } */
        $this->row = 2; // 从第二行开始
        return $this;
    }
    
    //添加表内容
    public function addData($data)
    {
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $value) {
                // 单元格内容写入
                $this->sheet->setCellValue($dataCol . $this->row, $value);
                $dataCol++;
            }
            $this->row++;
        }
        return $this;
    }
    
    /**
     * 导出EXCEL
     * @param array $header
     * @param array $data
     * @param string $fileName
     * @param string $ext
     * @param bool $isUse
     */
    public function exportFile( array $header = [],array $data = [],string $fileName,string $ext = 'xlsx',bool $isUseAliYunOss = true)
    {
        $this->__init();
        $this->setHeader($header);
        $this->addData($data);
        if( $isUseAliYunOss ) {
            return $this->saveAndUploadAliYunOss($fileName);
        }
        
        return Normal::returnCode(Normal::FAIL,"不好意思小伙伴，当前下载文件方式不太支持，需要去查询PHPoffice官方教程实现");
    }
    
    //保存临时文件在从浏览器自动下载到本地
    public function saveAndUploadAliYunOss(string $fileName, string $ext = 'xlsx')
    {
        $filePath   = $fileName.".".$ext;
        //进行切割
        $path       = \explode("/",$filePath);
        $path       = array_filter($path);
        $fileName   = end($path);
        $filePath   = \implode("/",$path);
        $writer     = IOFactory::createWriter($this->spreadsheet,ucfirst($ext));
        //保存到服务器的临时文件下
        $writer->save($fileName);
        //将文件转字符串
        $contents = file_get_contents($fileName);
        //删除临时文件
        unlink($fileName);
        return $this->uploadByContents($contents,$filePath);
    }
}
